package mwa.cs.rq.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.DefaultAddressDAO;
import mwa.cs.dao.GenDocDAO;
import mwa.cs.dao.ReceiveCodeDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestQuoteDAO;
import mwa.cs.dao.RequestTypeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.VatRateDAO;
import mwa.cs.database.Database;
import mwa.cs.model.DefaultAddress;
import mwa.cs.model.Request;
import mwa.cs.model.RequestQuote;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS63000Srvl
 */
public class CS63000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS63000Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
	
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		String vaDefaultAddress = request.getParameter("vaDefaultAddress");
		String vaProcessType = request.getParameter("process_type");
		if ( vaProcessType != null && vaProcessType.equals("getReceiveCode")) {
			getReceiveCode(request, response);
		} else if ( vaProcessType != null && vaProcessType.equals("getRequestType")){
			getRequestType(request, response);
		} else if (vaProcessType != null && vaProcessType.equals("saveData")){
			saveData(request, response);
		} else if (vaProcessType != null && vaProcessType.equals("getRequest")){
			getRequest(request, response);
		} else if (vaDefaultAddress != null && vaDefaultAddress.equals("yes")){
			getDefaultAddressData(request, response);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void getDefaultAddressData(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String[] vaDefaultAddressArray = null;
		Database db = new Database();
		DefaultAddressDAO voDefaultAddressDAO = new DefaultAddressDAO(db);
		DefaultAddress voDefaultAddress = voDefaultAddressDAO.getDefaultAddressBySiteId(vnSiteId);
		vaDefaultAddressArray = new String[4];
		vaDefaultAddressArray[0] = voDefaultAddress.getVaProvinceCode();
		vaDefaultAddressArray[1] = voDefaultAddress.getVaDistrictCode();
		vaDefaultAddressArray[2] = voDefaultAddress.getVaCityCode();
		vaDefaultAddressArray[3] = voDefaultAddress.getVaPostCode();
		PrintWriter voOut = response.getWriter();
		try {
			JSONObject voObject = new JSONObject();			
			JSONArray voList = new JSONArray();
			if (vaDefaultAddressArray != null) {
				for (int i = 0; i < vaDefaultAddressArray.length; i ++) {
					voList.add(vaDefaultAddressArray[i]);
				}
			}
			voObject.put("vaDefaultAddressArray", voList);
			voOut.print(voObject.toJSONString());
		} finally {
			db.close();
			voOut.close();
		}	
	}

	@SuppressWarnings("unchecked")
	public void getRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaRequestDescription = "";
		String vaName = "";
		String vaRequestDetail = "";
		String vaContactHomeNumber = "";
		String vaContactAddress = "";
		String vaContactCityCode = "";
		String vaContactDistrictCode = "";
		String vaContactProvinceCode = "";
		String vaContactPostCode = "";
		String vaContactTelephone = "";
		String vaRequestNum = "";
		
		Database db = new Database();
		PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		RequestDAO voRequestDAO = new RequestDAO(db);
		RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);
		String vaRequestNumber = request.getParameter("request_number");
		Map<String, Object> voMap =  voRequestDAO.getRequest(vnSiteId, vaRequestNumber);
		DecimalFormat voFormatter = new DecimalFormat("#########0.00");
		if(voMap != null){
		if(voMap.get("REQUEST_TYPE") != null){
			vaRequestDescription = voMap.get("REQUEST_TYPE").toString();
		}
		if(voMap.get("APPLICANT_NAME") != null){
			vaName = voMap.get("APPLICANT_NAME").toString();
		}
		if(voMap.get("DESCRIPTION") != null){
			vaRequestDetail = voMap.get("DESCRIPTION").toString();
		}
		if(voMap.get("CONTACT_HOME_NUMBER") != null){
			vaContactHomeNumber = voMap.get("CONTACT_HOME_NUMBER").toString();
		}
		if(voMap.get("CONTACT_ADDRESS") != null){
			vaContactAddress = voMap.get("CONTACT_ADDRESS").toString();
		}
		if(voMap.get("CONTACT_CITY_CODE") != null){
			vaContactCityCode = voMap.get("CONTACT_CITY_CODE").toString();
		}
		if(voMap.get("CONTACT_DISTRICT_CODE") != null){
			vaContactDistrictCode = voMap.get("CONTACT_DISTRICT_CODE").toString();
		}
		if(voMap.get("CONTACT_PROVINCE_CODE") != null){
			vaContactProvinceCode = voMap.get("CONTACT_PROVINCE_CODE").toString();
		}
		if(voMap.get("CONTACT_POST_CODE") != null){
			vaContactPostCode = voMap.get("CONTACT_POST_CODE").toString();
		}
		if(voMap.get("CONTACT_TELEPHONE") != null){
			vaContactTelephone = voMap.get("CONTACT_TELEPHONE").toString();
		}
		if(voMap.get("REQUEST_NUMBER") != null){
			vaRequestNum = voMap.get("REQUEST_NUMBER").toString();
		}
		voObject.put("message", "yes");	
		}else{
			voObject.put("message", "no");	
		}
		voObject.put("request_description", vaRequestDescription);
		voObject.put("name", vaName);
		voObject.put("request_detail",vaRequestDetail );
		voObject.put("contact_home_number", vaContactHomeNumber);
		voObject.put("contact_address", vaContactAddress);
		voObject.put("contact_city_code", vaContactCityCode);
		voObject.put("contact_district_code", vaContactDistrictCode);
		voObject.put("contact_province_code", vaContactProvinceCode);
		voObject.put("contact_post_code", vaContactPostCode);
		voObject.put("contact_telephone", vaContactTelephone);
		voObject.put("request_num", vaRequestNum);
	
		
		List<Map<String, Object>> voResult = voRequestQuoteDAO.getRequestQuote(vnSiteId, vaRequestNumber);

		
		String[] voReceiveCode = new String[voResult.size()];
		String[] voReceiveAmount = new String[voResult.size()];
		for (int i = 0; i < voResult.size(); i++) {
			voMap = voResult.get(i);
			voReceiveCode[i] = voMap.get("RECEIVE_CODE").toString();
			voReceiveAmount[i] = voMap.get("RECEIVE_AMOUNT").toString() ;
		}
		JSONArray voListReceiveCode = new JSONArray();
		if (voReceiveCode != null) {
			for (int i = 0; i < voReceiveCode.length; i++) {
				voListReceiveCode.add(voReceiveCode[i]);
			}
		}
		JSONArray voListReceiveAmount = new JSONArray();
		if (voReceiveAmount != null) {
			for (int i = 0; i < voReceiveAmount.length; i++) {
				voListReceiveAmount.add(voFormatter.format(Double.parseDouble(voReceiveAmount[i])));
			}
		}
		voObject.put("receive_code", voListReceiveCode);
		voObject.put("receive_amount", voListReceiveAmount);
		db.close();
		voOut.print(voObject.toJSONString());
	}
	
	@SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Database db = new Database();
		PrintWriter out = response.getWriter();
		JSONObject voObject = new JSONObject();
		try{
			db.beginTransaction();	
		GenDocDAO voGenDocDAO = new GenDocDAO(db);
		String vaRequestNumber = voGenDocDAO.generatingNextRQDoc(vnSiteId, JDate.getMonth(), JDate.getYear());
		String vaRequestGroup = "1";
		String vaRequestType = request.getParameter("request_description");
		String vaApplicantName = request.getParameter("name").trim();
		String vaApplicantHomeNumber = null;
		String vaApplicantAddress = null;
		String vaApplicantCityCode = null;
		String vaApplicantDistrictCode = null;
		String vaApplicantProvinceCode = null;
		String vaApplicantPostCode = null;
		String vaApplicantTelephone = null;
		String vaDescription = request.getParameter("request_detail").trim();
		String vaAccount = null;
		String vaPName = null;
		String vaFName = null;
		String vaLName = null;
		String vaCardId = null;
		String vaHouseId = null;
		String vaHomeNumber = null;
		String vaAddress = null;
		String vaCityCode = null;
		String vaDistrictCode = null;
		String vaProvinceCode = null;
		String vaPostCode = null;
		String vaTelephone = null;
		String vaContactName = null;
		String vaContactHomeNumber = request.getParameter("contact_home_number").trim();
		String vaContactAddress = request.getParameter("contact_address").trim();
		String vaContactCityCode = request.getParameter("contact_city_code");
		String vaContactDistrictCode = request.getParameter("contact_district_code");
		String vaContactProvinceCode = request.getParameter("contact_province_code");
		String vaContactPostCode = request.getParameter("contact_post_code").trim();
		String vaContactTelephone = request.getParameter("contact_telephone").trim();
		String vaAllowance = null;
		double vnWastewaterCharge = 0;
		double vnGarbageCharge = 0;
		double vnOtherCharge = 0;
		String vaDocumentType = null;
		String vaDocumentReference = null;
		String vaCustomerClass = null;
		String vaCustomerType = null;
		String vaMeterSize = null;
		String vaMeterBrand = null;
		String vaMeterSerialNumber = null;
		String vaMeterNumber = null;
		String vaMeterInstallDate = null;
		String vaMeterDate = null;
		String vaStatus = "1";
		String vaReasonCancel = null;
		String vaReasonClose = null;
		int vnInsertUserId = vnUserId;
		String vaInsertDate = JDate.getDate();
		String vaInsertTime = JDate.getTime();
		int vnUpdateUserId = 0;
		String vaUpdateDate = null;
		String vaUpdateTime = null;
		
		String vaCharge = request.getParameter("charge");
		String vaRequestNum = request.getParameter("request_num");
		String voReceiveCode[] = request.getParameterValues("receive_code[]");
		String voReceiveAmount[]= request.getParameterValues("receive_amount[]");
		RequestDAO voRequestDAO = new RequestDAO(db);
		RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		Request poRequest = new Request(vnSiteId, vaRequestNumber, vaRequestGroup, vaRequestType, vaApplicantName, vaApplicantHomeNumber, vaApplicantAddress, vaApplicantCityCode, vaApplicantDistrictCode, vaApplicantProvinceCode, vaApplicantPostCode, vaApplicantTelephone, vaDescription, vaAccount, vaPName, vaFName, vaLName, vaCardId, vaHouseId, vaHomeNumber, vaAddress, vaCityCode, vaDistrictCode, vaProvinceCode, vaPostCode, vaTelephone, vaContactName, vaContactHomeNumber, vaContactAddress, vaContactCityCode, vaContactDistrictCode, vaContactProvinceCode, vaContactPostCode, vaContactTelephone, vaAllowance, vnWastewaterCharge, vnGarbageCharge, vnOtherCharge, vaDocumentType, vaDocumentReference, vaCustomerClass, vaCustomerType, vaMeterSize, vaMeterBrand, vaMeterSerialNumber, vaMeterNumber, vaMeterInstallDate, vaMeterDate, vaStatus, vaReasonCancel, vaReasonClose, vnInsertUserId, vaInsertDate, vaInsertTime, vnUpdateUserId, vaUpdateDate, vaUpdateTime);
		
		String vaCondition = "request_number = "+vaRequestNum;
		voRequestDAO.deleteRequest(vaCondition);
		voRequestQuoteDAO.deleteRequestQuote(vaCondition);
		voRequestDAO.insertRequest(poRequest);
		DecimalFormat dfm = new DecimalFormat("0.00");
		if(vaCharge.equals("yes")){
		double vnVatRat = Double.parseDouble(voVatRateDAO.getVatRate(vnSiteId, JDate.getDate()).get("RATE").toString());
			for(int i=0;i<voReceiveCode.length;i++){
				if(voReceiveCode[i] != null && !voReceiveCode[i].equals("") && !voReceiveAmount[i].equals("0") && !voReceiveAmount[i].equals("")){
					String vaReceiveCode = voReceiveCode[i];
					double vnReceiveAmount = Double.parseDouble(voReceiveAmount[i]);
					vnReceiveAmount = new Double(dfm.format(vnReceiveAmount)).doubleValue();
					double vnVatAmount =  vnReceiveAmount * vnVatRat;
					vnVatAmount  = new Double(dfm.format(vnVatAmount)).doubleValue();
					double vnTotalAmount = vnReceiveAmount + vnVatAmount;
					vnTotalAmount  = new Double(dfm.format(vnTotalAmount)).doubleValue();
					RequestQuote voRequestQuote = new RequestQuote(vnSiteId, vaRequestNumber, vaReceiveCode, vnReceiveAmount, vnVatAmount, vnTotalAmount, vnInsertUserId, vaInsertDate, vaInsertTime, vnUpdateUserId, vaUpdateDate, vaUpdateTime);
					voRequestQuoteDAO.insertRequestQuote(voRequestQuote);
					
				}
					
				}
			
		}
			db.commit();
			voObject.put("message", "success");
			voObject.put("RequestNumber", vaRequestNumber);
			
		} catch (Exception e) {
			db.rollback();
			System.out.println("pabz"+ e.getMessage());
			SMErrorLogDAO.getInstance().addLog(0, "CS63000", JDate.getDate(), JDate.getTime(),vnUserId, "CS63000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			voObject.put("message", "error");
			e.printStackTrace();
		} finally{
			db.close();
		}
		
		out.print(voObject.toJSONString());
		
	}

	@SuppressWarnings("unchecked")
	public void getReceiveCode(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Database db = new Database();
		PrintWriter out = response.getWriter();
		String[] vaMessage = null, vaValue = null;
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		String paCondition = "receive_code != 21 AND receive_code != 22 ORDER BY receive_code ASC";
		List<Map<String, Object>> voResult = voReceiveCodeDAO
				.findReceiveCodeByCondition(vnSiteId, paCondition);

		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
		
		for (int i = 0; i < voResult.size(); i++) {
			Map<String, Object> voObject = voResult.get(i);
			vaValue[i] = voObject.get("RECEIVE_CODE").toString();
			vaMessage[i] = voObject.get("RECEIVE_CODE")+" "+voObject.get("DESCRIPTION");
		}
		
		JSONObject voObject = new JSONObject();
		JSONArray voListMessages = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i++) {
				voListMessages.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voListMessages);
		JSONArray voListValues = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i++) {
				voListValues.add(vaValue[i]);
			}
		}
		voObject.put("values", voListValues);
		
		db.close();
		out.print(voObject.toJSONString());

	}
	@SuppressWarnings("unchecked")
	public void getRequestType(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Database db = new Database();
		PrintWriter out = response.getWriter();
		String[] vaMessage = null, vaValue = null;
		RequestTypeDAO voRequestTypeDAO = new RequestTypeDAO(db);
		String paCondition = "request_group = 1 ORDER BY request_type ASC";
		List<Map<String, Object>> voResult = voRequestTypeDAO.findRequestTypeByCondition(vnSiteId, paCondition);

		vaValue = new String[voResult.size()];
		vaMessage = new String[voResult.size()];
		
		for (int i = 0; i < voResult.size(); i++) {
			Map<String, Object> voObject = voResult.get(i);
			vaValue[i] = voObject.get("REQUEST_TYPE").toString();
			vaMessage[i] = voObject.get("REQUEST_TYPE")+" "+voObject.get("REQUEST_DESCRIPTION");
		}
		
		JSONObject voObject = new JSONObject();
		JSONArray voListMessages = new JSONArray();
		if (vaMessage != null) {
			for (int i = 0; i < vaMessage.length; i++) {
				voListMessages.add(vaMessage[i]);
			}
		}
		voObject.put("messages", voListMessages);
		JSONArray voListValues = new JSONArray();
		if (vaValue != null) {
			for (int i = 0; i < vaValue.length; i++) {
				voListValues.add(vaValue[i]);
			}
		}
		voObject.put("values", voListValues);
		db.close();
		out.print(voObject.toJSONString());

	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
